/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CadCategoria.java
 *
 * Created on 13/10/2011, 12:17:58
 */
package visao;

import Nivel.Nivel;
import Nivel.NivelNaoCadastradoException;
import categoria.Categoria;
import categoria.CategoriaNaoCadastradoException;
import fachada.FachadaBDR;
import java.awt.Color;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import setor.Setor;
import setor.SetorNaoCadastradoException;
import subSetor.SubSetor;
import subSetor.SubSetorNaoCadastradoException;
import util.CamposObrigatoriosException;
import util.ErroAcessoRepositorioException;
import util.KeyValue;

/**
 *
 * @author Administrador
 */
public class CadCategoria extends javax.swing.JFrame {

    /** Creates new form CadCategoria */
    public CadCategoria() {
        initComponents();

        this.setLocationRelativeTo(null);
        this.setIconImage(new ImageIcon(getClass().getResource("/Imagens/Categoria.gif")).getImage());

    }

    /** Creates new form CadCategoria */
    public CadCategoria(int idCategoria) {
        initComponents();
        this.setLocationRelativeTo(null);
        this.setIconImage(new ImageIcon(getClass().getResource("/Imagens/Categoria.gif")).getImage());

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            // obtendo a categoria
            Categoria objCategoria = objFachadaBDR.procurarCategoria(idCategoria);

            // Obtendo o setor
            SubSetor objSubSetor = objFachadaBDR.procurarSubSetor(objCategoria.getSubSetor().getIdSubSetor());

            Nivel objNivel = objFachadaBDR.procurarNivel(objCategoria.getNivel().getIdNivel());


            jTextField_idCodigo.setText(String.valueOf(objCategoria.getIdCategoria()));
            jTextField_Descricao.setText(objCategoria.getNome());
            jCheckBox_Status.setSelected(objCategoria.getStatusCategoria());
            jComboBox_SubSetor.setSelectedItem(new KeyValue(objSubSetor.getDescricaoSubSetor(), Integer.toString(objSubSetor.getIdSubSetor())));
            jComboBox_idnivel.setSelectedItem(new KeyValue(objNivel.getDescricaoNivel(), Integer.toString(objNivel.getIdNivel())));



        } catch (NivelNaoCadastradoException ex) {

            jLabel_Menssagem.setText(ex.getMessage());
            jLabel_Menssagem.setForeground(Color.red);

        } catch (SubSetorNaoCadastradoException ex) {

            jLabel_Menssagem.setText(ex.getMessage());
            jLabel_Menssagem.setForeground(Color.red);

        } catch (CategoriaNaoCadastradoException ex) {
            jLabel_Menssagem.setText(ex.getMessage());
            jLabel_Menssagem.setForeground(Color.red);
        } catch (CamposObrigatoriosException ex) {
            Logger.getLogger(CadCategoria.class.getName()).log(Level.SEVERE, null, ex);
            jLabel_Menssagem.setText(ex.getMessage());
            jLabel_Menssagem.setForeground(Color.red);
        } catch (ErroAcessoRepositorioException ex) {
            Logger.getLogger(CadCategoria.class.getName()).log(Level.SEVERE, null, ex);
            jLabel_Menssagem.setText(ex.getMessage());
            jLabel_Menssagem.setForeground(Color.red);
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel_idCodigo = new javax.swing.JLabel();
        jLabel_Nome = new javax.swing.JLabel();
        jTextField_Descricao = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jCheckBox_Status = new javax.swing.JCheckBox();
        jButton_Ok = new javax.swing.JButton();
        jButton_Cancelar = new javax.swing.JButton();
        jLabel_Menssagem = new javax.swing.JLabel();
        jTextField_idCodigo = new javax.swing.JTextField();
        jComboBox_SubSetor = new javax.swing.JComboBox();
        jComboBox_idnivel = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();

        setTitle("Categoria");
        setResizable(false);

        jLabel_idCodigo.setText("Codigo :");

        jLabel_Nome.setText("Nome :");

        jLabel4.setText("Sub Setor :");

        jCheckBox_Status.setSelected(true);
        jCheckBox_Status.setText("Altivo");

        jButton_Ok.setText("OK");
        jButton_Ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_OkActionPerformed(evt);
            }
        });

        jButton_Cancelar.setText("Cancelar");
        jButton_Cancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_CancelarActionPerformed(evt);
            }
        });

        jTextField_idCodigo.setText("0");
        jTextField_idCodigo.setEnabled(false);

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            List<SubSetor> listSubSetor = objFachadaBDR.listarSubSetorAtivos();
            jComboBox_SubSetor.addItem(new KeyValue("--- Favor Selecionar ---", "0"));
            for (SubSetor objSubSetor : listSubSetor) {
                jComboBox_SubSetor.addItem(new KeyValue(objSubSetor.getDescricaoSubSetor(), Integer.toString(objSubSetor.getIdSubSetor())));
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        jComboBox_SubSetor.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox_SubSetorItemStateChanged(evt);
            }
        });
        jComboBox_SubSetor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox_SubSetorActionPerformed(evt);
            }
        });
        jComboBox_SubSetor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                jComboBox_SubSetorPropertyChange(evt);
            }
        });
        jComboBox_SubSetor.addVetoableChangeListener(new java.beans.VetoableChangeListener() {
            public void vetoableChange(java.beans.PropertyChangeEvent evt)throws java.beans.PropertyVetoException {
                jComboBox_SubSetorVetoableChange(evt);
            }
        });

        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            List<Nivel> listNivel = objFachadaBDR.listarNivelAtivos();
            jComboBox_idnivel.addItem(new KeyValue("--- Favor Selecionar ---", "0"));
            for (Nivel objNivel : listNivel) {
                jComboBox_idnivel.addItem(new KeyValue(objNivel.getDescricaoNivel(), Integer.toString(objNivel.getIdNivel())));
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

        jLabel1.setText("Nivel Sub Setor:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel_Menssagem, javax.swing.GroupLayout.PREFERRED_SIZE, 490, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton_Ok, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel_Nome)
                                .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel_idCodigo)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton_Cancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jTextField_Descricao, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jComboBox_SubSetor, javax.swing.GroupLayout.Alignment.LEADING, 0, 366, Short.MAX_VALUE)
                                .addComponent(jComboBox_idnivel, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTextField_idCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 161, Short.MAX_VALUE)
                                .addComponent(jCheckBox_Status)
                                .addGap(70, 70, 70)))))
                .addContainerGap(29, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(44, 44, 44)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextField_idCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel_idCodigo)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(31, 31, 31)
                        .addComponent(jCheckBox_Status)))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel_Nome)
                    .addComponent(jTextField_Descricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jComboBox_SubSetor, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(33, 33, 33)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox_idnivel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(47, 47, 47)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton_Ok)
                    .addComponent(jButton_Cancelar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel_Menssagem, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(35, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void jButton_OkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_OkActionPerformed
        // TODO add your handling code here:
        int idCategoria = Integer.parseInt(jTextField_idCodigo.getText());
        String nome = jTextField_Descricao.getText();
        Boolean status = jCheckBox_Status.isSelected();
        int idSubSetor = Integer.parseInt(((KeyValue) jComboBox_SubSetor.getSelectedItem()).getValue());
        int idNivel = Integer.parseInt(((KeyValue) jComboBox_idnivel.getSelectedItem()).getValue());
        try {
            FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();
            SubSetor objSubSetor = objFachadaBDR.procurarSubSetor(idSubSetor);
            Nivel objNivel = objFachadaBDR.procurarNivel(idNivel);

            Categoria objCategoria = new Categoria(idCategoria, objSubSetor, objNivel, nome, status, null);

            // Se o id da categoria não foi informado a categoria será cadastrada
            if (idCategoria == 0) {
                objFachadaBDR.cadastrarCategoria(objCategoria);
            } else // se não a categoria será atualizada
            {
                objFachadaBDR.atualizarCategoria(objCategoria);
            }

            String acao = (idCategoria == 0) ? "Cadastrada" : "Editada";
            jLabel_Menssagem.setText("Categoria " + acao + " Com Sucesso!!!");
            jLabel_Menssagem.setForeground(Color.BLACK);

            if (idCategoria == 0) {
                jTextField_Descricao.setText("");
                jCheckBox_Status.setSelected(false);
                jComboBox_SubSetor.setSelectedIndex(0);
                jComboBox_idnivel.setSelectedIndex(0);

            }

        } catch (NivelNaoCadastradoException ex) {

            jLabel_Menssagem.setText(ex.getMessage());
            jLabel_Menssagem.setForeground(Color.red);

        } catch (SubSetorNaoCadastradoException ex) {

            jLabel_Menssagem.setText(ex.getMessage());
            jLabel_Menssagem.setForeground(Color.red);

        } catch (CamposObrigatoriosException ex) {

            jLabel_Menssagem.setText(ex.getMessage());
            jLabel_Menssagem.setForeground(Color.red);
        } catch (ErroAcessoRepositorioException ex) {

            jLabel_Menssagem.setText(ex.getMessage());
            jLabel_Menssagem.setForeground(Color.red);
        }
    }//GEN-LAST:event_jButton_OkActionPerformed

    private void jButton_CancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_CancelarActionPerformed
        // TODO add your handling code here:

        int cancelar = JOptionPane.showConfirmDialog(null, "Deseja cancelar ?");
        if (cancelar == JOptionPane.YES_OPTION) {

            dispose();

        } else {
        }


    }//GEN-LAST:event_jButton_CancelarActionPerformed

private void jComboBox_SubSetorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_SubSetorActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_jComboBox_SubSetorActionPerformed

private void jComboBox_SubSetorPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jComboBox_SubSetorPropertyChange
}//GEN-LAST:event_jComboBox_SubSetorPropertyChange

private void jComboBox_SubSetorVetoableChange(java.beans.PropertyChangeEvent evt)throws java.beans.PropertyVetoException {//GEN-FIRST:event_jComboBox_SubSetorVetoableChange
}//GEN-LAST:event_jComboBox_SubSetorVetoableChange

private void jComboBox_SubSetorItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox_SubSetorItemStateChanged
    try {
        FachadaBDR objFachadaBDR = FachadaBDR.getInstancia();

        int idSubSetor = Integer.parseInt(((KeyValue) jComboBox_SubSetor.getSelectedItem()).getValue());

        if (idSubSetor > 0) {
            // Listando as descrição produtos
            List<Nivel> listNivel = objFachadaBDR.procurarNivelPorDescricaoPorSubSetor("", idSubSetor);

            // removendo todos os itens 
            jComboBox_idnivel.removeAllItems();

            // atualizando todos os itens
            jComboBox_idnivel.addItem(new KeyValue("--- Favor Selecionar ---", "0"));
            for (Nivel objNivel : listNivel) {
                jComboBox_idnivel.addItem(new KeyValue(objNivel.getDescricaoNivel(), Integer.toString(objNivel.getIdNivel())));
            }
            jComboBox_idnivel.revalidate();
        }
    } catch (Exception e) {
        jLabel_Menssagem.setText(e.getMessage());
        jLabel_Menssagem.setForeground(Color.red);
    }
}//GEN-LAST:event_jComboBox_SubSetorItemStateChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new CadCategoria().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton_Cancelar;
    private javax.swing.JButton jButton_Ok;
    private javax.swing.JCheckBox jCheckBox_Status;
    private javax.swing.JComboBox jComboBox_SubSetor;
    private javax.swing.JComboBox jComboBox_idnivel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel_Menssagem;
    private javax.swing.JLabel jLabel_Nome;
    private javax.swing.JLabel jLabel_idCodigo;
    private javax.swing.JTextField jTextField_Descricao;
    private javax.swing.JTextField jTextField_idCodigo;
    // End of variables declaration//GEN-END:variables
}
